/**
 * @Description: 版本更新
 * @author ourslookAdmin
 * @date 2019-04-28 12:58:56
 */
import React, { Fragment } from 'react';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Divider,
  Form,
  Input,
  Avatar,
  Radio,
  Row,
  Select,
  Spin,
  List,
  Table,
  BackTop,
  Timeline,
  Tooltip,
  Icon,
} from 'antd';
import Modal from 'drag-modal';
import { formatMessage, FormattedMessage } from 'umi/locale';
import ReactDOM from 'react-dom';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission, rulesReg, rulesRemote } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import coming from '@/decorator/coming';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;
const IsNull = null;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(() => ({}))
class InfVersionInfo extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    { title: '更新平台', dataIndex: 'deviceName', width: 120, align: 'center', sorter: false },
    { title: '版本名称', dataIndex: 'versionname', width: 120, align: 'center', sorter: false },
    {
      title: '强制更新',
      dataIndex: 'isforceupdatename',
      width: 120,
      align: 'center',
      sorter: false,
    },
    { title: '下载地址', dataIndex: 'downloadurl', width: 360, align: 'center', sorter: false },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 230,
      align: 'center',
      sorter: true,
      index: 'createTime',
    },
    {
      title: '操作',
      dataIndex: '',
      width: 130,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.getData(record);
              this.showModel();
            }}
          >
            <Tooltip
              title={
                <FormattedMessage id="ours.curd.list.updateRecord" defaultMessage="发布记录" />
              }
            >
              <Icon type="align-center" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: InfVersionInfo.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
      sourceList: [],
      synLoadling: false,
      isDisabled: false,
      theList: [
        {
          title: '版本代码',
          dataIndex: 'versioncode',
          key: 'versioncode',
          width: 150,
        },
        {
          title: '更新平台',
          dataIndex: 'deviceName',
          key: 'deviceName',
          width: 150,
        },
        {
          title: '版本名称',
          dataIndex: 'versionname',
          key: 'versionname',
          width: 150,
        },
        {
          title: '强制更新',
          key: 'isforceupdatename',
          dataIndex: 'isforceupdatename',
          width: 150,
        },

        {
          title: '下载地址',
          key: 'downloadurl',
          dataIndex: 'downloadurl',
        },
      ],
      theData: [],
      theLog: null,
    };
  }

  // 筛选条件
  static getFormList = () => [];

  componentDidMount() {
    this.requestList();
    this.getDeviceList();
  }

  componentWillUnmount() {}

  getDeviceList = () => {
    requestPromise(`${getWebPath('dictInfo/deviceList')}`, {
      method: 'GET',
    }).then(res => {
      if (res) {
        const adTypes = res || [];
        const backSource = [
          { id: '', name: '请选择反馈平台' },
          ...adTypes.map(e => ({ id: e.code, name: e.name })),
        ];

        const { formList: formListNew } = this.state;
        this.setState({
          formList: formListNew,
          sourceList: backSource,
          theData: backSource, // 此操作 为了查看跟新日志时，theData如果为空会导致报错，所以此处给theData 随便赋个值
        });
      }
    });
  };

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {},
      showList: 2,
    });
  };

  update = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.getData(selectedRows[0]);
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  showModel = () => {
    this.setState({
      visible: true,
    });
  };

  handleOk = e => {
    this.setState({
      visible: false,
    });
  };

  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };

  showLog = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'showLog',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getLog(selectedRows[0]);
    this.getInfo(selectedRows[0].id);
  };

  getData = row => {
    requestPromise(`${getWebPath(`/infversioninfo/list?device=${row.device}`)}`, {
      method: 'GET',
    }).then(res => {
      if (res) {
        const adTypes = res || [];
        const { formList: formListNew } = this.state;
        this.setState({
          formList: formListNew,
          theData: adTypes.page.list,
        });
      }
    });
  };

  getLog = row => {
    requestPromise(`${getWebPath(`/infversioninfo/list?device=${row.device}`)}`, {
      method: 'GET',
    }).then(res => {
      if (res) {
        const adTypes = res || [];
        const { formList: formListNew } = this.state;
        this.setState({
          formList: formListNew,
          theData: adTypes.page.list,
        });
      }
    });
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}infversioninfo/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const infVersionInfo = Object.assign(
      this.state.editModel,
      this.editForm.props.form.getFieldsValue()
    );

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = infVersionInfo.id == null ? '/infversioninfo/save' : '/infversioninfo/update';
        //对象删除一个属性
        //delete infVersionInfo.xxxxPros;

        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: infVersionInfo,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!infVersionInfo.id) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = id => {};

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  generatorWord = () => {
    // this.setState({synLoadling:true});
    this.setState({ isDisabled: true });
    const selectedRows = this.state.selectedRows;
    const tableNames = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      tableNames.push(selectedRows[i].tableName);
    }

    window.location.href = getWebPath(
      //`/infexpress/exportsExcelAll?params=${encodeURIComponent(selectedRows[0])}&isCvs=${true}&modelIds=${IsNull}`
      `/infversioninfo/outputword`
    );
    this.theInfo();
  };

  theInfo = () => {
    Modal.info({
      title: '提示:',
      content: (
        <div>
          <p>word导出中，请稍候...</p>
        </div>
      ),
      onOk() {},
    });
  };

  operateByIds = status => {};

  //========其他所有的处理方法，请在按照约定进行处理==========

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    if (this.props.location.query !== undefined) {
      if (this.props.location.query.deviceCode !== undefined) {
        this.params.deviceCode = this.props.location.query.deviceCode;
      }
    }
    requestLists(this, `${getWebPath()}infversioninfo/listByDevice`, this.params);
    //弹框
    if (this.props.location.query !== undefined) {
      if (this.props.location.query.deviceCode !== undefined) {
        const row = {
          device:this.props.location.query.deviceCode
        };
        this.getData(row);
        this.showModel();
      }
    }
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const firstButtonStyle = {
      style: {
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    const wordButtonStyle = {
      // 专门为导出word按钮做一个style
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <div>
          <Modal
            title="发布记录"
            visible={this.state.visible}
            onOk={this.handleOk}
            width={800}
            onCancel={this.handleCancel}
            footer={null}
          >
            <Timeline>
              {this.state.theData.map((item, index) => (
                <Timeline.Item>
                  <div style={{ display: 'flex' }}>
                    <h1>{item.versionname}</h1>&nbsp;&nbsp;
                    <p style={{ 'font-size': '12px', 'padding-top': '5px' }}>{item.createTime}</p>
                  </div>
                  {/*<p>更新平台：{item.deviceName}</p>*/}
                  <p>更新内容：{item.updatecontent}</p>
                  {/*<p>强制更新：{item.isforceupdatename}</p>*/}
                  {/*<p>上次更新：{item.updateDate}</p>*/}
                  <p>
                    下载地址：<a href={item.downloadurl}>点击下载</a>
                  </p>
                </Timeline.Item>
              ))}
            </Timeline>
          </Modal>
        </div>

        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <Fragment>
            <Button
              type="primary"
              icon="edit"
              {...firstButtonStyle}
              onClick={this.update}
              hidden={!hasPermission('infversioninfo:update')}
            >
              <FormattedMessage id="ours.curd.list.update" defaultMessage="修改" />
            </Button>
            <Button
              type="primary"
              icon="info-circle"
              {...style}
              onClick={this.view}
              hidden={!hasPermission('infversioninfo:info')}
            >
              查看
            </Button>

            <Button
              type="primary"
              icon="info-circle"
              {...style}
              onClick={this.showLog}
              hidden={!hasPermission('infversioninfo:info')}
            >
              更新日志
            </Button>

            <Button
              type="primary"
              icon="file-word"
              onClick={this.generatorWord}
              hidden={!hasPermission('sys:generator:code')}
              {...wordButtonStyle}
              disabled={this.state.isDisabled}
            >
              导出word
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="id"
              selectedIndexs={this.state.selectedIndexs}
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 900 }}
            />
          </div>
        </Card>

        <BackTop />

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                sourceList={this.state.sourceList}
                theList={this.state.theList}
                theData={this.state.theData}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default InfVersionInfo;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
    sourceList: PropTypes.object,
    theList: PropTypes.object,
    theData: PropTypes.object,
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
    sourceList: [],
    theList: [],
    theData: [],
  };

  constructor(props) {
    super(props);
    this.state = {
      // eslint-disable-next-line react/no-unused-state
      copied: false,
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {}

  onCopy = () => {
    this.showInfo();
    // eslint-disable-next-line react/no-unused-state
    this.setState({ copied: true });
  };

  showInfo = () => {
    Modal.info({
      title: '提示:',
      content: (
        <div>
          <p>复制成功！</p>
        </div>
      ),
      onOk() {},
    });
  };

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const copyButtonStyle = {
      // copy按钮
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Form layout="horizontal">
        <Row gutter={{ ...rowGutterPxLayout }}>
          {type !== 'showLog' && (
            <Col {...colSpanLayout}>
              <FormItem label="版本代码" {...formItemLayout}>
                {type === 'view'
                  ? model.versioncode
                  : getFieldDecorator('versioncode', {
                      initialValue: model.versioncode,
                      rules: [
                        {
                          required: true,
                          message: '版本代码必填',
                        },
                        rulesReg('number'),
                      ],
                    })(<Input type="text" autocomplete="off" placeholder="版本代码" />)}
              </FormItem>
            </Col>
          )}
          {type !== 'showLog' && (
            <Col {...colSpanLayout}>
              <FormItem label="版本名称" {...formItemLayout}>
                {type === 'view'
                  ? model.versionname
                  : getFieldDecorator('versionname', {
                      initialValue: model.versionname,
                      rules: [
                        {
                          required: true,
                          message: '必填',
                        },
                        {
                          whitespace: true,
                          message: '不能包含空白符',
                        },
                        {
                          max: 100,
                          message: '最长100个字符',
                        },
                      ],
                    })(<Input type="text" autocomplete="off" maxlength={100} placeholder="" />)}
              </FormItem>
            </Col>
          )}
          {type !== 'showLog' && (
            <Col {...colSpanLayout}>
              <FormItem label="更新平台" {...formItemLayout}>
                {type === 'view'
                  ? model.deviceName
                  : getFieldDecorator('device', {
                      initialValue: Number.parseFloat(model.device),
                    })(
                      <Select
                        style={{ width: '100%' }}
                        placeholder="更新平台"
                        {...inputCodeDisabled}
                      >
                        {uiUtils.getOptionList(this.props.sourceList)}
                      </Select>
                    )}
              </FormItem>
            </Col>
          )}
          {type !== 'showLog' && (
            <Col {...colSpanLayout}>
              <FormItem label="强制更新" {...formItemLayout}>
                {type === 'view'
                  ? model.isforceupdatename
                  : getFieldDecorator('isforceupdate', {
                      initialValue: model.isforceupdate,
                    })(
                      <RadioGroup>
                        <Radio value={0}>否</Radio>
                        <Radio value={1}>是</Radio>
                      </RadioGroup>
                    )}
              </FormItem>
            </Col>
          )}

          {type !== 'showLog' && (
            <Col {...colSpanLayout}>
              <FormItem label="上次更新." {...formItemLayout}>
                {type === 'view'
                  ? model.updateDate
                  : getFieldDecorator('updateDate', {
                      initialValue: model.updateDate,
                      rules: [
                        {
                          required: true,
                          message: '上次跟新日期.必填',
                        },
                      ],
                    })(
                      <Input
                        type="text"
                        autocomplete="off"
                        {...inputCodeDisabled}
                        placeholder="上次跟新日期."
                      />
                    )}
              </FormItem>
            </Col>
          )}
          {type !== 'showLog' && (
            <Col {...colSpanLayout}>
              <FormItem label="下载地址" {...formItemLayout}>
                {type === 'view'
                  ? model.downloadurl
                  : getFieldDecorator('downloadurl', {
                      initialValue: model.downloadurl,
                      rules: [
                        {
                          required: false,
                          message: '必填',
                        },
                        {
                          whitespace: true,
                          message: '不能包含空白符',
                        },
                        {
                          max: 200,
                          message: '最长200个字符',
                        },
                      ],
                    })(
                      <Input
                        type="text"
                        autocomplete="off"
                        {...inputCodeDisabled}
                        maxlength={200}
                        placeholder=""
                      />
                    )}
              </FormItem>

              {type !== 'showLog' && (
                <CopyToClipboard onCopy={this.onCopy} text={model.downloadurl}>
                  <Button {...copyButtonStyle}>复制下载地址</Button>
                </CopyToClipboard>
              )}
            </Col>
          )}
          {type !== 'showLog' && (
            <Col {...colSpanLayout}>
              <FormItem label="更新内容" {...formItemLayout}>
                {type === 'view'
                  ? model.updatecontent
                  : getFieldDecorator('updatecontent', {
                      initialValue: model.updatecontent,
                    })(
                      <TextArea
                        autosize={{ minRows: 3, maxRows: 10 }}
                        maxlength={500}
                        placeholder="更新内容"
                      />
                    )}
              </FormItem>
            </Col>
          )}

          {type === 'view' && (
            <Col {...rowGutterPxLayout}>
              {/*<Table*/}
              {/*  columns={this.props.theList}*/}
              {/*  dataSource={this.props.theData}*/}
              {/*  expandedRowRender={record => <p style={{ margin: 0 }}>{record.updatecontent}</p>}*/}
              {/*/>*/}
            </Col>
          )}

          {type === 'showLog' && (
            <Col {...rowGutterPxLayout}>
              <List
                itemLayout="horizontal"
                dataSource={this.props.theData}
                renderItem={item => (
                  <List.Item>
                    <List.Item.Meta
                      avatar={<Avatar src="" />}
                      title={<a href="https://ant.design">{item.versionname}</a>}
                      description={item.updatecontent}
                    />
                  </List.Item>
                )}
              />
            </Col>
          )}
        </Row>
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
